﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Shapes;
using System.Xml.Linq;
using AteCapybara;
using Newtonsoft.Json;
using QRCoder;
using Arch.DBLINK;
using System.Windows.Controls.Primitives;
using ATECapybara;


namespace ATEDiagnoser
{
    public partial class ATECapybara : Form
    {
        private string SettingPath = @"Data\Setting.json";

        private string TypePath = @"Data\WLAN款型表.xlsx";

        private string PasswordPath = @"Data\Password.xlsx";

        private Setting Setting;

        private DataTable BoardTypeTable;

        private DataTable TaiweiPasswordTable;

        private DataTable AccountPasswordTable;

        private Diagnoser DGN = new Diagnoser();

        private List<ComboBox> ListComboBox = new List<ComboBox>();

        private List<CheckBox> ListCheckBox = new List<CheckBox>();

        private List<ListBox> ListListBox = new List<ListBox>();

        /*————————————————————————————————————————————————————————————————————————————————*/

        #region 初始化和结束
        public ATECapybara()
        {
            InitializeComponent();

        }
        /// <summary>
        /// 加载文件
        /// </summary>
        private void Load_File()
        {
            //反序列化json配置
            if (!File.Exists(SettingPath))
            {
                MsgShow.Error($"配置文件{SettingPath}不存在！");
                this.Close();
            }
            string temp = File.ReadAllText(SettingPath);
            Setting = JsonConvert.DeserializeObject<Setting>(temp);

            try
            {
                //加载款型excel
                if (!File.Exists(TypePath))
                {
                    MsgShow.Error($"款型表{TypePath}不存在！");
                    this.Close();
                }
                Excel ex = new Excel(TypePath);
                BoardTypeTable = ex.QueryTable("款型");
            }
            catch (Exception e)
            {
                MsgShow.Error("请确保先安装AccessDatabaseEngine.exe。具体错误：" + e.Message);
                if (File.Exists("AccessDatabaseEngine.exe"))
                {
                    DGN.Execute("AccessDatabaseEngine.exe");
                }
                this.Close();
            }    


            //密码表excel
            if (!File.Exists(PasswordPath))
            {
                MsgShow.Error($"Password表{PasswordPath}不存在！");
                this.Close();
            }
            Excel ex2 = new Excel(PasswordPath);
            TaiweiPasswordTable = ex2.QueryTable("台位");
            AccountPasswordTable = ex2.QueryTable("账号");
        }
        /// <summary>
        /// 程序加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //窗体大小
            this.Size = new Size(1042,720);

            //——————————加载文件——————————
            Load_File();

            //——————————界面的值赋值——————————
            //【选项卡】
            tabControl1.SelectedIndex = Setting.UserOper["initial_index"].JsonToInt32();

            //【1.ATE】
            if (Directory.Exists("Pic//Capybara"))
            {
                string path = "Pic//Capybara//Capybara";
                path += (int)DateTime.Now.DayOfWeek;
                if (DateTime.Now.Hour>23 || DateTime.Now.Hour<8)
                {
                    path += "e";
                }
                path += ".jpg";
                if (File.Exists(path))
                {
                    Capybara.Image = Image.FromFile(path);
                }
                else
                {
                    MsgShow.Error("Capybara不在家，无法工作~");
                    this.Close();
                }
            }
            else
            {
                MsgShow.Error("Capybara不在家，无法工作~");
                this.Close();
            }
            //
            //ate版本赋值
            foreach (var item in Setting.ATE)
            {
                if (item.Key != "Common")
                {
                    ate_version.Items.Add(item.Key);
                }
            }
            ListComboBox.Add(ate_version);
            //账号下拉框赋值
            foreach (DataRow item in AccountPasswordTable.Rows)
            {
                if (item["权限"].ToString().Trim()== "公开")
                {
                    account_public.Items.Add(item["描述"]);
                }
            }
            ListComboBox.Add(account_public);

            //【2.FT】
            ft_dut_Search();
            ListCheckBox.Add(ft_isOpenLog);
            ft_boardtype.Items.Clear();
            foreach (DataRow item in BoardTypeTable.Rows)
            {
                ft_boardtype.Items.Add(item["索引"].ToString()+"."+item["款型"].ToString() +"(" +item["目标"].ToString()+")");
            }
            ft_boardtype.SelectedIndex = 0;

            //【5.ST】


            //【6.本地电脑】
            ListListBox.Add(local_moreOper);
            ListListBox.Add(local_moreDirFile);
            //自动添加本地电脑的盘符
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (var item in drives)
            {
                local_moreDirFile.Items.Add(item.Name);
            }

            //【快捷菜单】
            Setting.JudgeHangsDevice();
            DGN.HangsPath = Setting["hangs_device"] + Setting["hangs_dir"];
            //读取hangs文件夹加入到快捷菜单中去
            TraverseFolder(hangs_hangs, DGN.HangsPath);
            
            //【统一赋值】
            //combox
            foreach (var item in ListComboBox)
            {
                item.SelectedIndex = Setting.UserOper[item.Name+"_index"].JsonToInt32();
            }
            //checkBox
            foreach (var item in ListCheckBox)
            {
                item.Checked = Convert.ToBoolean(Setting.UserOper[item.Name]);
            }
            //listbox
            foreach(var item in ListListBox)
            {
                var t = Setting[item.Name].Split(';');
                item.Items.AddRange(t);
            }
            RefreshLabel();
            RefreshLocal();
            //【款型】中的datatable
            RefreshDataTable();
            //使得DUT树上有值
            ft_dut_name_SelectedIndexChanged(null, null);
            //粘贴板第一次老是出错，先让他出错一次
            try
            {
                Clipboard.SetText("capybara");
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// 程序关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //界面的值保存
            //选项卡
            Setting.UserOper["initial_index"] = tabControl1.SelectedIndex.ToString();

            //ATE
            Setting.UserOper["ate_version_index"] = ate_version.SelectedIndex.ToString();

            //【统一保存值】
            //combox
            foreach (var item in ListComboBox)
            {
                Setting.UserOper[item.Name + "_index"]= item.SelectedIndex.ToString();
            }
            //checkBox
            foreach (var item in ListCheckBox)
            {
                Setting.UserOper[item.Name] = item.Checked.ToString();
            }
            //序列化json并保存
            string temp = JsonConvert.SerializeObject(Setting);
            File.WriteAllText(SettingPath, temp);
        }
        /// <summary>
        /// 设置label的值
        /// </summary>
        /// <param name="label"></param>
        private void SetLB(Label label)
        {
            label.Text = Setting[label.Name];
        }
        /// <summary>
        /// 设置label的值
        /// 形如：
        /// WiFi测试仪
        /// 192.168.10.254
        /// </summary>
        /// <param name="label"></param>
        /// <param name="button"></param>
        private void SetLB(Label label,Button button)
        {
            label.Text = Setting[label.Name] + "\r\n" + Setting[button.Name];
        }
        /// <summary>
        /// 刷新label
        /// </summary>
        private void RefreshLabel()
        {
            SetLB(ft_lb);
            SetLB(ft_23_lb, ft_23);
            SetLB(ft_24_lb, ft_24);
            SetLB(ft_switch_lb, ft_switch);
            SetLB(ft_wifixml);
            ft_wifixml.Text += "\\";

            SetLB(bosa_lb);
            SetLB(bosa_17_lb, bosa_17);
            SetLB(bosa_18_lb, bosa_18);
            SetLB(bosa_19_lb, bosa_19);
            SetLB(bosa_20_lb, bosa_20);
            SetLB(bosa_21_lb, bosa_21);
            SetLB(bosa_22_lb, bosa_22);
            SetLB(bosa_23_lb, bosa_23);
            SetLB(bosa_24_lb, bosa_24);
            SetLB(bosa_switch_lb, bosa_switch);

            SetLB(tss_lb);
            SetLB(tss_22_lb, tss_22);
            SetLB(tss_23_lb, tss_23);
            SetLB(tss_24_lb, tss_24);
            SetLB(tss_switch_lb, tss_switch);

            SetLB(st_lb);
            SetLB(st_g_lb);
            SetLB(st_o_lb);
            SetLB(st_22_lb, st_22);
            SetLB(st_23_lb, st_23);
            SetLB(st_24_lb, st_24);
            SetLB(st_switch_lb, st_switch);
        }
        /// <summary>
        /// 刷新【款型】中的datatable
        /// </summary>
        private void RefreshDataTable()
        {
            dataGridView1.DataSource = BoardTypeTable;
            dataGridView1.Columns[1].Frozen = true;
        }
        #endregion

        #region 公共事件
        /// <summary>
        /// 所有按钮的公共事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Bt_Click(object sender, EventArgs e)
        {
            if (sender is Button)
            {
                DGN.Execute(Setting[((Button)sender).Name]);
            }
            else if (sender is ToolStripItem)
            {
                DGN.Execute(Setting[((ToolStripItem)sender).Name]);
            }
        }
        /// <summary>
        /// 直接根据名字进行操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Bt_Click2(object sender, EventArgs e)
        {
            if (sender is ToolStripItem)
            {
                DGN.Execute(((ToolStripItem)sender).Name);
            }
        }
        /// <summary>
        /// 右键菜单中的关于打开ATE的
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ATE_Click(object sender, EventArgs e)
        {
            var t = now_ATE[((ToolStripItem)sender).Name];
            if (t.StartsWith("\\"))
            {
                t = "[ate]" + t;
            }
            DGN.Execute(t);
        }
        /// <summary>
        /// 所有linklabel公共事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Link_Clicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DGN.Execute(Setting[((LinkLabel)sender).Name]);
        }
        #endregion

        /*————————————————————————————————————————————————————————————————————————————————*/

        #region 1.ATE
        //—————————————————   ATE版本选择   —————————————————
        /// <summary>
        /// 现在使用的ATE版本
        /// </summary>
        private CATE now_ATE;

        /// <summary>
        /// 选择ATE版本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ATE_Version_cb_SelectedIndexChanged(object sender, EventArgs e)
        {
            //判断ATE在哪个盘：不存在则不会改变
            now_ATE = Setting.ATE[ate_version.Text];
            Setting.JudgeATEDevice(ate_version.Text,now_ATE);
            //展示赋值
            ate_dir.Text = now_ATE["device"] + now_ATE["dir"];
            DGN.ATEPath = ate_dir.Text;
            shortcut.Text = "打开" + ate_version.Text;
        }

        /// <summary>
        /// 点击ate地址，打开ATE主文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ate_dir_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DGN.Execute(ate_dir.Text);
        }

        //—————————————————   账号   —————————————————
        /// <summary>
        /// 选择账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cb_account_public_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (DataRow item in AccountPasswordTable.Rows)
            {
                if (item["描述"].ToString() == account_public.Text)
                {
                    rtb_account.Text = item["账号"].ToString() ;
                    rtb_password.Text = item["密码"].ToString();
                    rtb_other.Text = item["其他"].ToString();
                    break;
                }
            }
        }

        /// <summary>
        /// 选择账号、密码、备注时，全选，并复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void richTextboxSelect(object sender, MouseEventArgs e)
        {
            System.Windows.Forms.TextBoxBase richTextBox = sender as RichTextBox;
            if (!string.IsNullOrEmpty(richTextBox.Text))
            {
                // 选择全部文本
                richTextBox.SelectAll();
                try
                {
                    Clipboard.SetText(richTextBox.Text.Trim());
                }
                catch (Exception)
                {
                    try
                    {
                        Clipboard.SetText(richTextBox.Text.Trim());
                    }
                    catch (Exception ee)
                    {
                        MsgShow.Error("复制出错！" + ee.Message);
                    }
                    
                }
            }
        }
        QRCodeShow qc;
        /// <summary>
        /// 特权账号按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SpecailBtn_Click(object sender, EventArgs e)
        {
            if (qc == null || qc.IsDisposed)
            {
                qc = new QRCodeShow(AccountPasswordTable);
                qc.Show();
            }
            else
            {
                qc.Focus();
            }
        }
        #endregion

        #region 2.FT
        private void ft_all_Click(object sender, EventArgs e)
        {

        }
        //—————————————————   打开文件夹   —————————————————
        /// <summary>
        /// 搜索wifixml文件夹里面的文件夹
        /// </summary>
        private void ft_dut_Search()
        {
            if (Directory.Exists(Setting["ft_wifixml"]))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(Setting["ft_wifixml"]);
                DirectoryInfo[] directories = directoryInfo.GetDirectories();
                HashSet<string> list = new HashSet<string>();
                //去除数字后的东西
                foreach (DirectoryInfo d in directories)
                {
                    string temp = d.Name;
                    temp = Regex.Replace(temp, @"\d+.*", match => match.Value.Substring(0, match.Value.Length - (temp.Length - match.Groups[0].Index)));
                    list.Add(temp);
                }
                //加入到list里面
                ft_dut_name.Items.Clear();
                foreach (var item in list)
                {
                    //只找含DUT文件夹
                    if (item.ToUpper().Contains("DUT"))
                    {
                        ft_dut_name.Items.Add(item);
                    }
                }
                if (ft_dut_name.Items.Count > 0)
                {
                    ft_dut_name.SelectedIndex = 0;
                }
            }
        }

        /// <summary>
        /// 打开wifixml的dut
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ft_dut_Click(object sender, EventArgs e)
        {
            var buttonName = ((Button)sender).Name;
            var path = ft_wifixml.Text +ft_dut_name.Text + buttonName[buttonName.Length-1];
            if (ft_isOpenLog.Checked)
            {
                path += Setting["ft_wifixml_log"];
            }
            DGN.Execute(path);
        }

        /// <summary>
        /// 展示DUT
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ft_dut_name_SelectedIndexChanged(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            for (int i = 1; i < 10; i++)
            {
                var path = ft_wifixml.Text + ft_dut_name.Text + i.ToString();
                if (Directory.Exists(path))
                {
                    var root = treeView1.Nodes.Add(ft_dut_name.Text + i.ToString());
                    var directoryInfo = new DirectoryInfo(path);
                    foreach (var item in directoryInfo.GetFiles())
                    {
                        if (item.Extension.ToLower() == ".sw_lic")
                        {
                            root.Nodes.Add(item.Name);
                        }
                    }
                }
            }
            treeView1.ExpandAll();

        }
        //—————————————————   校线损BOM   —————————————————
        /// <summary>
        /// 校线损BOM切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ft_boardtype_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = ft_boardtype.SelectedIndex;
            ft_bom.Text = BoardTypeTable.Rows[index]["单板编码"].ToString();
            ft_calbom.Text = BoardTypeTable.Rows[index]["校线损单板编码"].ToString();
        }
        /// <summary>
        /// 清空加密文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            var temp = MsgShow.Ask_YesNo($"是否要清空加密文件夹ENCRYPTION？");
            if (temp == DialogResult.Yes)
            {
                string path = "D:\\ENCRYPTION";
                if (Directory.Exists(path))
                {
                    var dirs = Directory.GetDirectories(path);
                    foreach (string dir in dirs)
                    {
                        Directory.Delete(dir, true); // 递归删除子目录
                    }
                    var files = Directory.GetFiles(path);
                    foreach (string file in files)
                    {
                        File.Delete(file);
                    }
                    DGN.Execute(path);
                }
                else
                {
                    MsgShow.Hint($"不存在D:\\ENCRYPTION，无须删除！");
                }
            }
        }
        /// <summary>
        /// 清空本编码的校准数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            var temp = MsgShow.Ask_YesNo($"是否要清空{ft_calbom.Text}编码的校准数据？");
            if (temp == DialogResult.Yes)
            {
                string path = ft_wifixml.Text + ft_calbom.Text + ".xml";
                if (File.Exists(path))
                {
                    File.Delete(path);
                    DGN.Execute(ft_wifixml.Text);
                }
                else
                {
                    MsgShow.Hint($"没有{ft_calbom.Text}编码的校准数据，无须删除！");
                }
            }
        }
        //—————————————————   极致license   —————————————————
        /// <summary>
        /// 文件拖入时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_DragDrop(object sender, DragEventArgs e)
        {
            //DialogResult t;
            //if (ft_isToBLE_DUT.Checked)
            //{
            //    t = MsgShow.Ask_YesNo("是否要将该文件分发到每个BLE_DUT？");
            //}
            //else
            //{
            //    t = MsgShow.Ask_YesNo("是否要将该文件分发到每个DUT？");
            //}
            //if (t == DialogResult.Yes)
            //{
            //    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            //    StringBuilder sb = new StringBuilder();
            //    for (int i = 1; i < 8; i++)
            //    {
            //        string destpath = Setting["ft_wifixml"];
            //        if (ft_isToBLE_DUT.Checked)
            //        {
            //            destpath += Setting["ft_BLE_DUT" + i];
            //        }
            //        else
            //        {
            //            destpath += Setting["ft_DUT" + i];
            //        }
            //        if (Directory.Exists(destpath))
            //        {
            //            string name = System.IO.Path.GetFileName(files[0]);
            //            File.Copy(files[0], destpath + "\\" + name);
            //            sb.Append(i + ",");
            //        }
            //    }
            //    if (sb.Length == 0)
            //    {
            //        MsgShow.OK($"分发失败。请检查DUT文件夹是否存在。");
            //    }
            //    else
            //    {
            //        sb.Remove(sb.Length - 1, 1);
            //        if (ft_isToBLE_DUT.Checked)
            //        {
            //            MsgShow.OK($"分发完成。已分发至机柜BLE_DUT{sb.ToString()}");
            //        }
            //        else
            //        {
            //            MsgShow.OK($"分发完成。已分发至机柜DUT{sb.ToString()}");
            //        }
            //    }

            //}

        }

        /// <summary>
        /// 拖放效果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_DragEnter_1(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy; // 或者其他效果
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        #endregion

        #region 3.BOSA
        private void bosa_all_Click(object sender, EventArgs e)
        {

        }

        //—————————————————   链路光功率检查   —————————————————
        /// <summary>
        /// 带负数、小数点的数字的正则
        /// </summary>
        private string numRegex = @"^-?\d+(\.\d+)?$";

        /// <summary>
        /// 判断是否是数字，为空也返回false
        /// </summary>
        /// <param name="temp"></param>
        /// <returns></returns>
        private bool isNum(string temp)
        {
            if (!string.IsNullOrEmpty(temp) && Regex.IsMatch(temp, numRegex))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 将范围（形如[-3,9]）转换成min和max
        /// </summary>
        /// <param name="rangeTxt"></param>
        /// <returns></returns>
        private (double min, double max) Split_Range(string rangeTxt)
        {
            string[] range_splitor = new string[] { "(", ")", "[", "]", "," };
            var range = rangeTxt.Split(range_splitor, StringSplitOptions.RemoveEmptyEntries);
            double min = Convert.ToDouble(range[0]);
            double max = Convert.ToDouble(range[1]);
            return (min, max);
        }

        /// <summary>
        /// 判断给定的数字是否在范围内
        /// </summary>
        /// <param name="temp"></param>
        /// <returns></returns>
        private bool isInRange(string temp, string range)
        {
            return isInRange(Convert.ToDouble(temp), range);
        }
        private bool isInRange(double temp, string range)
        {
            (var mina, var maxa) = Split_Range(range);
            if (temp < mina || temp > maxa)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 错误时，控件的展示
        /// </summary>
        /// <param name="isCorrect"></param>
        /// <param name="tb"></param>
        private void SetErrorOrNot(bool isCorrect, Control tb)
        {
            if (isCorrect)
            {
                tb.ForeColor = Color.Black;
            }
            else
            {
                tb.ForeColor = Color.Red;
            }
        }

        private void power1_TextChanged(object sender, EventArgs e)
        {
            power2_TextChanged(null, null);
            osc_TextChanged(null, null);
            //检查power1是否在范围内
            string temp1 = power1.Text.Trim();
            if (isNum(temp1))
            {
                SetErrorOrNot(isInRange(temp1, power1_range.Text), power1);
            }
        }

        private void power2_TextChanged(object sender, EventArgs e)
        {
            string temp1 = power1.Text.Trim();
            string temp2 = power2.Text.Trim();
            if (isNum(temp2))
            {
                //检查power2是否在范围内
                SetErrorOrNot(isInRange(temp2, power2_range.Text), power2);
                //检查power_loss是否在范围内
                if (isNum(temp1))
                {
                    double result = Convert.ToDouble(temp1) - Convert.ToDouble(temp2);
                    power_loss.Text = result.ToString("F3");
                    SetErrorOrNot(isInRange(result, power_loss_range.Text), power_loss);
                }
            }
        }

        private void osc_TextChanged(object sender, EventArgs e)
        {
            string temp1 = power1.Text.Trim();
            string temp2 = osc.Text.Trim();
            if (isNum(temp2))
            {
                //检查osc是否在范围内
                SetErrorOrNot(isInRange(temp2, osc_range.Text), osc);
                //检查osc_loss是否在范围内
                if (isNum(temp1))
                {
                    double result = Convert.ToDouble(temp1) - Convert.ToDouble(temp2);
                    osc_loss.Text = result.ToString("F3");
                    SetErrorOrNot(isInRange(result, osc_loss_range.Text), osc_loss);
                }
            }
        }

        private void optical_TextChanged(object sender, EventArgs e)
        {
            string temp1 = optical.Text.Trim();
            if (isNum(temp1))
            {
                //检查optical是否在范围内
                SetErrorOrNot(isInRange(temp1, optical_range.Text), optical);
            }
        }

        private void opm_TextChanged(object sender, EventArgs e)
        {
            string temp1 = att.Text.Trim();
            string temp2 = opm.Text.Trim();
            if (isNum(temp2))
            {
                //检查opm是否在范围内
                SetErrorOrNot(isInRange(temp2, opm_range.Text), opm);
                //检查att_loss是否在范围内
                if (isNum(temp1))
                {
                    double result = Convert.ToDouble(temp1) - Convert.ToDouble(temp2);
                    att_loss.Text = result.ToString("F3");
                    SetErrorOrNot(isInRange(result, att_loss_range.Text), att_loss);
                }
            }
        }

        /// <summary>
        /// 清空复原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            power1.Text = "-";
            power2.Text = "-";
            osc.Text = "-";
            optical.Text = "-";
            opm.Text = "-";
            power_loss.Text = "0";
            osc_loss.Text = "0";
            att_loss.Text = "0";
        }
        #endregion

        #region 4.TSS
        private void tss_all_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 5.ST
        private void st_all_Click(object sender, EventArgs e)
        {

        }

        ST_QRCode stqr;
        /// <summary>
        /// 展示ST-QRCode生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            if (stqr == null || stqr.IsDisposed)
            {
                stqr = new ST_QRCode();
                stqr.Show();
            }
            else
            {
                stqr.Focus();
            }
        }


        ST_BluetoothShow bs;
        /// <summary>
        /// 展示蓝牙
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (bs == null || bs.IsDisposed)
            {
                bs = new ST_BluetoothShow();
                bs.Show();
            }
            else
            {
                bs.Focus();
            }
        }

        FT_CodeTransfer stcode;
        /// <summary>
        /// 长短条码转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            if (stcode == null || stcode.IsDisposed)
            {
                stcode = new FT_CodeTransfer();
                stcode.Show();
            }
            else
            {
                stcode.Focus();
            }
        }
        #endregion

        #region 6.本地电脑
        /// <summary>
        /// 刷新本地计算机-显示IP、hostname
        /// </summary>
        public void RefreshLocal()
        {
            //赋值hostname
            local_modifyHostName.Text = Dns.GetHostName();
            //赋值登录名
            local_modifyRemoteAccount.Text = Environment.UserName;
            local_modifyPassword.Text = "";
            //赋值password
            foreach (DataRow item in TaiweiPasswordTable.Rows)
            {
                if (item[0].ToString().Trim().ToLower() == local_modifyHostName.Text.Trim().ToLower())
                {
                    local_modifyPassword.Text = item[1].ToString().Trim();
                    break;
                }
            }
            //赋值ip地址
            local_modifyIP.Text = "";
            IPAddress[] addresses = Dns.GetHostAddresses(local_modifyHostName.Text); // 获取本机IP地址列表
            foreach (IPAddress address in addresses)
            {
                // 判断是否是IPv4地址
                if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    local_modifyIP.Text += address.ToString() + "\r\n";
                }
            }
        }
        /// <summary>
        /// 更多...
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listbox_Double_Click(object sender, EventArgs e)
        {
            var t = sender as ListBox;
            DGN.Execute(t.SelectedItem.ToString());
        }
        /// <summary>
        /// ping 其他ip
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pt_Click(object sender, EventArgs e)
        {
            string temp = pt_tb.Text.Trim();
            if (Regex.IsMatch(temp, @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"))
            {
                DGN.Execute_CMD("ping -t "+temp);
            }
            else
            {
                MsgShow.Error("IP地址错误！");
            }
            
        }
        /// <summary>
        /// 192.168.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                pt_tb.Text = "192.168.";
            }
            else
            {
                pt_tb.Text = "";
            }
        }
        #endregion

        #region 7.款型
        /// <summary>
        /// 点击单元格，自动复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是有效单元格
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                // 将单元格值复制到剪贴板
                try
                {
                    string cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    if (!string.IsNullOrEmpty(cellValue))
                    {
                        Clipboard.SetText(cellValue);
                    }
                }
                catch (Exception)
                {
                    try
                    {
                        string cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                        if (!string.IsNullOrEmpty(cellValue))
                        {
                            Clipboard.SetText(cellValue);
                        }
                    }
                    catch (Exception ee)
                    {
                        MsgShow.Error("复制出错！" + ee.Message);
                    }
                    
                }
            }
        }
        #endregion

        /*————————————————————————————————————————————————————————————————————————————————*/

        #region 快捷菜单
        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //刷新ft的wifixml查找的文件夹
            ft_dut_Search();
            //刷新展示的DUT
            ft_dut_name_SelectedIndexChanged(null, null);
            //刷新本地电脑的hostname、ip
            RefreshLocal();
            //刷新快捷菜单的hangs下的文件夹
            hangs_hangs.DropDownItems.Clear();
            TraverseFolder(hangs_hangs, DGN.HangsPath);
        }
        private void 打开ATE主文件夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ate_dir_LinkClicked(ate_dir, null);
        }
        private void 清空脚本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var temp = MsgShow.Ask_YesNo($"是否要清空{ate_version.Text}的本地脚本？(重新测试时会重新下载)");
            if (temp == DialogResult.Yes)
            {
                string path = DGN.ATEPath + now_ATE["script"];
                var dirs = Directory.GetDirectories(path);
                foreach (string dir in dirs)
                {
                    Directory.Delete(dir, true); // 递归删除子目录
                }
                var files = Directory.GetFiles(path);
                foreach (string file in files)
                {
                    File.Delete(file);
                }
                DGN.Execute(path);
            }
        }
        /// <summary>
        /// 自动添加hangs文件夹的内容到快捷菜单中去
        /// </summary>
        /// <param name="tsi"></param>
        /// <param name="folderPath"></param>
        void TraverseFolder(ToolStripMenuItem tsi, string folderPath)
        {
            if (Directory.Exists(folderPath))
            {
                string[] files = Directory.GetFiles(folderPath);
                string[] subFolders = Directory.GetDirectories(folderPath);
                foreach (string subFolder in subFolders)
                {
                    string name = System.IO.Path.GetFileName(subFolder);
                    ToolStripMenuItem temp = new ToolStripMenuItem(name);
                    temp.Name = subFolder;
                    temp.Click += Bt_Click2;
                    tsi.DropDownItems.Add(temp);
                    var t = Setting["hangs_moreDir"].Split(';');
                    foreach (string s in t)
                    {
                        if (!string.IsNullOrEmpty(s) && name == s.Trim())
                        {
                            TraverseFolder(temp, subFolder);
                        }
                    }
                }
                foreach (string file in files)
                {
                    string name = System.IO.Path.GetFileName(file);
                    ToolStripMenuItem temp = new ToolStripMenuItem(name);
                    temp.Name = file;
                    var t = Setting["hangs_ignoreFile"].Split(';');
                    foreach (string s in t)
                    {
                        if (string.IsNullOrEmpty(s) || !Regex.IsMatch(name, s))
                        {
                            temp.Click += Bt_Click2;
                        }
                    }
                    tsi.DropDownItems.Add(temp);
                }
            }
            
        }
        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void stop_service_Click(object sender, EventArgs e)
        {
            //使用ATE自带的停止服务
            ATE_Click(sender, e);
            Thread.Sleep(2000);
            //再手动下发java停止服务
            //DGN.Execute_CMD("taskkill /F /IM java.exe");
            foreach (var process in Process.GetProcessesByName("java.exe"))
            {
                process.Kill();
            }
            foreach (var process in Process.GetProcessesByName("javaw.exe"))
            {
                process.Kill();
            }
        }
        private void 清空浏览器缓存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //关闭chrome浏览器
            foreach (var process in Process.GetProcessesByName("chrome"))
            {
                process.Kill();
            }
            //清空浏览器缓存
            string userName = Environment.UserName;
            string cachePath = System.IO.Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "Google","Chrome","User Data","Default","Cache");
            try
            {
                // 确保缓存目录存在
                if (Directory.Exists(cachePath))
                {
                    // 删除所有文件
                    foreach (string filePath in Directory.GetFiles(cachePath))
                    {
                        File.Delete(filePath);
                    }
                    // 删除所有目录
                    foreach (var item in Directory.GetDirectories(cachePath))
                    {
                        Directory.Delete(item,true);
                    }
                    MsgShow.OK("缓存已清空。");
                    DGN.Execute(cachePath);
                }
                else
                {
                    MsgShow.Error($"缓存目录{cachePath}不存在。");
                }
            }
            catch (Exception ex)
            {
                MsgShow.Error(ex.Message);
            }
        }
        private void 清空加密文件夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 特权操作
        private bool isDiagnose = false;
        /// <summary>
        /// 按下Ctrl+A显示特权账号
        /// 按下Ctrl+P切到ping -t
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Special_KeyDown(object sender, KeyEventArgs e)
        {
            // Ctrl+A显示特权账号
            if (!isDiagnose && e.Control && e.KeyCode == Keys.A)
            {
                Input_Password ip = new Input_Password(Setting.UserOper["password"]);
                ip.SuccessAction = () =>
                {
                    tabControl1.SelectedIndex = 0;
                    isDiagnose = true;
                    SpecialShow();
                    timer1.Enabled = true;
                    timer1.Start();
                };
                ip.ShowDialog();
            }
            // ESC退出诊断模式
            else if (isDiagnose && e.KeyCode == Keys.Escape)
            {
                isDiagnose = false;
                SpecialDisappear();
                timer1.Stop();
                timer1.Enabled = false;
            }
            // 按下Ctrl+P切到ping -t
            if (e.Control && e.KeyCode == Keys.P)
            {
                tabControl1.SelectedIndex = 5;
                pt_tb.Focus();
            }
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (isDiagnose)
            {
                isDiagnose = false;
                SpecialDisappear();
            }
            timer1.Stop();
            timer1.Enabled = false;
        }

        /// <summary>
        /// 特权展示的东西
        /// </summary>
        private void SpecialShow()
        {
            SpecialBtn.Visible = true;
            install_capybaras_data.Visible = true;
        }
        /// <summary>
        /// 特权消失的东西
        /// </summary>
        private void SpecialDisappear()
        {
            SpecialBtn.Visible = false;
            install_capybaras_data.Visible = false;
        }


        #endregion

    }
}
